package edu.gyc.rbacdb.auth;

import edu.gyc.rbacdb.model.Menu;
import edu.gyc.rbacdb.model.Role;
import edu.gyc.rbacdb.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Component
public class CustomFilterSecuritySource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    MenuService menuService;

    //路径匹配
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override  //根据请求的url分析url对应的角色
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl=((FilterInvocation)object).getRequestUrl();

        List<Menu> menus=menuService.getAllMenusWithRole();
        for (Menu menu : menus) {
            if (antPathMatcher.match(menu.getPattern(), requestUrl)) {
                List<Role> roles=menu.getRoles();
                String[] rolesStr = new String[roles.size()];
                for (int i=0;i<roles.size();i++) {
                    rolesStr[i] = roles.get(i).getName();
                }
                return SecurityConfig.createList(rolesStr);
            }
        }
        return SecurityConfig.createList("ROLE_login"); //ROLE_login标记
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
